from django.contrib import admin
from django.utils.html import format_html
from .models import Restaurant, Order, MenuItem

@admin.register(Restaurant)
class RestaurantAdmin(admin.ModelAdmin):
    list_display = ('name', 'address', 'rating', 'is_open', 'created_at', 'show_image')
    list_filter = ('is_open', 'rating')
    search_fields = ('name', 'address')
    readonly_fields = ('rating',)
    list_per_page = 20
    date_hierarchy = 'created_at'
    
    def show_image(self, obj):
        if obj.image:
            return format_html('<img src="{}" width="50" height="50" style="border-radius: 50%;" />', obj.image.url)
        return "无图片"
    show_image.short_description = '餐厅图片'

@admin.register(Order)
class OrderAdmin(admin.ModelAdmin):
    list_display = ('id', 'user', 'restaurant', 'total_price', 'status', 'created_at', 'payment_status')
    list_filter = ('status', 'created_at')
    search_fields = ('user__username', 'restaurant__name')
    readonly_fields = ('trade_no',)
    list_per_page = 20
    date_hierarchy = 'created_at'
    ordering = ('-created_at',)
    
    fieldsets = (
        ('基本信息', {
            'fields': ('user', 'restaurant')
        }),
        ('订单状态', {
            'fields': ('status', 'total_price')
        }),
        ('支付信息', {
            'fields': ('trade_no',),
            'classes': ('collapse',)
        }),
    )
    
    def payment_status(self, obj):
        if obj.status == '已支付':
            return format_html('<span style="color: green;">✓ 已支付</span>')
        elif obj.status == '待支付':
            return format_html('<span style="color: orange;">⌛ 待支付</span>')
        elif obj.status == '已取消':
            return format_html('<span style="color: red;">✗ 已取消</span>')
        return obj.status
    payment_status.short_description = '支付状态'

    actions = ['mark_as_paid', 'mark_as_cancelled']
    
    def mark_as_paid(self, request, queryset):
        updated = queryset.update(status='已支付')
        self.message_user(request, f'成功将 {updated} 个订单标记为已支付')
    mark_as_paid.short_description = '标记为已支付'
    
    def mark_as_cancelled(self, request, queryset):
        updated = queryset.update(status='已取消')
        self.message_user(request, f'成功将 {updated} 个订单标记为已取消')
    mark_as_cancelled.short_description = '标记为已取消'
    
    def get_readonly_fields(self, request, obj=None):
        if obj and obj.status == '已支付':  # 如果订单已支付，限制字段编辑
            return self.readonly_fields + ('status', 'total_price', 'user', 'restaurant')
        return self.readonly_fields

@admin.register(MenuItem)
class MenuItemAdmin(admin.ModelAdmin):
    list_display = ('name', 'restaurant', 'price', 'category', 'is_available', 'created_at')
    list_filter = ('restaurant', 'category', 'is_available')
    search_fields = ('name', 'restaurant__name')
    list_per_page = 20
    date_hierarchy = 'created_at'
